require "proto/union/message/ReqAskJoinUnionMessage"
require "proto/union/message/ReqCreateUnionMessage"
require "proto/union/message/ReqDisbandUnionMessage"
require "proto/union/message/ReqHandleJoinListMessage"
require "proto/union/message/ReqJonUnionMessage"
require "proto/union/message/ReqQuitUnionMessage"
require "proto/union/message/ReqUnionInfoListMessage"
require "proto/union/message/ReqUnionInfoMessage"
require "proto/union/message/ReqModifyUnionSettingMessage"
require "proto/union/message/ReqModifyJMemberJobMessage"
require "proto/union/message/ReqSearchUnionMessage"
require "proto/union/message/ReqUnionByIdInfoMessage"
require "proto/union/message/ReqKickMemberInfoMessage"
require "proto/union/message/ReqUnionRenameMessage"
require "proto/union/message/ReqUnionEventLogMessage"
require "proto/union/message/ReqUseHeroRankMessage"
require "proto/union/message/ReqUnionBossBattleMessage"
require "proto/union/message/ReqUnionBossInfoMessage"
require "proto/union/message/ReqApplyUnionsMessage"
require "proto/union/message/ReqSearchAllianceMessage"
require "proto/union/message/ReqAllianceInfoListMessage"
require "proto/union/message/ReqAllianceReleaseMessage"
require "proto/union/message/ReqAllianceCancelMessage"
require "proto/union/message/ReqAllianceMergeMessage"
require "proto/union/message/ReqHandleAllianceJoinListMessage"
require "proto/union/message/ReqAllianceExitMessage"
require "proto/union/message/ReqAllianceExitCancelMessage"
require "proto/guild/task/message/ReqGuildTaskListInfoMessage"
require "proto/guild/task/message/ReqRecvGuildTaskAwardMessage"
require "proto/guild/task/message/ReqRecvGuildTaskBoxAwardMessage"
require "proto/guild/task/message/ReqRecvAllGuildTaskAwardMessage"

unionHandler = unionHandler or {}

--获取公会信息
function unionHandler.reqUnionInfoMessage()
    local req = ReqUnionInfoMessage.New();
    sendReqMessage(req);
end

--创建公会
function unionHandler.reqCreateUnion(unionName,msg)
    local req = ReqCreateUnionMessage.New();
    req.unionName = unionName;
    req.unionSetting = msg;
    sendReqMessage(req);
end

--加入公会
function unionHandler.reqJoinUnion(unionId)
    local req = ReqJonUnionMessage.New();
    req.unionId = unionId;
    sendReqMessage(req);
end

--请求修改工会设置
function unionHandler.reqModifyUnionSetting(unionId,msg)
    local req = ReqModifyUnionSettingMessage.New();
    req.unionId = unionId;
    req.unionSetting = msg;
    sendReqMessage(req);
end

--请求工会列表
function unionHandler.reqUnionInfoList()
    local req = ReqUnionInfoListMessage.New();
    sendReqMessage(req);
end

--请求退出工会
function unionHandler.reqQuitUnion(unionId)
    local req = ReqQuitUnionMessage.New();
    req.unionId = unionId;
    sendReqMessage(req);
end

--请求处理申请列表
function unionHandler.reqHandleJoinList(unionId,isAgree,ids)
    local req = ReqHandleJoinListMessage.New();
    req.unionId = unionId;
    req.isAgree = isAgree;
    req.ids = ids;
    if #ids > 1 then
        logicMgr.GuildManager.setJoinNum(true);
    else
        logicMgr.GuildManager.setJoinNum();
    end
    sendReqMessage(req);
end

--请求修改成员职位
function unionHandler.reqModifyJMemberJob(unionId,playerId,jobId)
    local req = ReqModifyJMemberJobMessage.New();
    req.unionId = unionId;
    req.playerId = playerId;
    req.jobId = jobId;
    sendReqMessage(req);
end

--请求查找工会
function unionHandler.reqSearchUnion(unionId,unionName,province,city)
    local req = ReqSearchUnionMessage.New();
    if unionId > 0 then
        req.searchType = 0;
    elseif unionName then
        req.searchType = 1;
    elseif province then
        req.searchType = 2;
    elseif city then
        req.searchType = 3;
    end
    req.unionId = unionId;
    req.unionName = unionName; 
    req.province = province;
    req.city = city;
    sendReqMessage(req);
end


--请求指定公会信息详情
function unionHandler.reqUnionByIdInfo(unionId)
    local req = ReqUnionByIdInfoMessage.New();
    req.unionId = unionId;
    sendReqMessage(req);    
end


--请求踢人
function unionHandler.reqKickMemberInfo(playerId)
    local req = ReqKickMemberInfoMessage.New();
    req.playerId = playerId;
    sendReqMessage(req);
end

--请求修改公会名称
function unionHandler.reqUnionRename(unionName)
    local req = ReqUnionRenameMessage.New();
    req.unionName = unionName;
    sendReqMessage(req);
end

--请求公会日志
function unionHandler.reqUnionEventLogs()
    local req = ReqUnionEventLogMessage.New();
    sendReqMessage(req);
end

--请求贡献榜
function unionHandler.reqUseHeroRank(unionId)
    local req = ReqUseHeroRankMessage.New();
    req.unionId = unionId;
    sendReqMessage(req);
end

--请求工会Boss战斗
function unionHandler.reqUnionBossBattle(param)
    if logicMgr.GuildManager.waitMessage then
        return
    end
    local req = ReqUnionBossBattleMessage.New();
    req.unionId = param.unionId;
    req.unionId2 = param.allianceId;
    req.bossId = param.bossId;
    req.formation = param.formation;
    sendReqMessage(req);
    logicMgr.GuildManager.waitMessage = true;
    print("公会boss战请求战斗")
end

--请求工会个人Boss信息
function unionHandler.reqUnionBossInfo(unionId, allianceId)
    local req = ReqUnionBossInfoMessage.New();
    req.unionId = unionId;
    req.unionId2 = allianceId;
    sendReqMessage(req);
end

--请求申请的工会列表
function unionHandler.ReqApplyUnions()
    local req = ReqApplyUnionsMessage.New();
    sendReqMessage(req);
end

-- 请求查找联盟
function unionHandler.sendReqSearchAlliance(unionId,unionName)
    local req = ReqSearchAllianceMessage.New();
    if unionId > 0 then
        req.searchType = 0;
    elseif unionName then
        req.searchType = 1;
    end
    req.unionId = unionId;
    req.unionName = unionName;
    sendReqMessage(req);
end

--请求联盟列表
function unionHandler.sendReqAllianceInfoList()
    local req = ReqAllianceInfoListMessage.New();
    sendReqMessage(req);
end

--发布联盟申请状态
function unionHandler.sendReqAllianceRelease()
    local req = ReqAllianceReleaseMessage.New();
    sendReqMessage(req);
end

--取消联盟申请状态
function unionHandler.sendReqAllianceCancel()
    local req = ReqAllianceCancelMessage.New();
    sendReqMessage(req);
end

--合并联盟申请
function unionHandler.sendReqAllianceMerge(unionId)
    local req = ReqAllianceMergeMessage.New();
    req.unionId = unionId;
    sendReqMessage(req);
end

--请求处理联盟申请列表
function unionHandler.sendReqHandleAllianceJoinList(isAgree, unionId)
    local req = ReqHandleAllianceJoinListMessage.New();
    req.isAgree = isAgree;
    req.unionId = unionId;
    sendReqMessage(req);
end

--解散联盟
function unionHandler.sendReqAllianceExit()
    local req = ReqAllianceExitMessage.New();
    sendReqMessage(req);
end

--撤销解散联盟
function unionHandler.ReqAllianceExitCancel()
    local req = ReqAllianceExitCancelMessage.New();
    sendReqMessage(req);
end

----------------------------------------------------
--- 公会科技相关逻辑
----------------------------------------------------
require "proto/uniontech/message/ReqUnionTechInfoMessage"
require "proto/uniontech/message/ReqUnionUpgradeTechMessage"
require "proto/uniontech/message/ReqUnionResetTechMessage"


--请求科技列表数据 
function unionHandler.sendReqReqUnionTechInfo()
    --print("unionHandler.sendReqReqUnionTechInfo-->")
    local req = ReqUnionTechInfoMessage.New()
    sendReqMessage(req)
end
-- 应答科技列表数据
unionHandler.union_tech_list_data = {}
function unionHandler.receiveResUnionTechInfo( msg )
    --print("unionHandler.receiveResUnionTechInfo-->", table.tostring(msg) )
    if msg and msg.state == 0 then
        if msg and msg.techs then 
            if unionHandler.union_tech_list_data == nil then
                unionHandler.union_tech_list_data = {}
            end
            local key = nil
            for _, v in pairs(msg.techs) do
                key = v.techId --+ v.lv  
                unionHandler.union_tech_list_data[key] = v
            end
        end
        unionHandler.refreshUnionTechAttr()

        if isOpenUI(PanelNames.UIGuildTech) then
            local ui_guild_tech = CtrlManager.GetCtrl(PanelNames.UIGuildTech) 
            ui_guild_tech.UpdateUnionTechInfoListData(msg) ---- 应答科技列表数据
        end
        partnerHandler.ReqHeroPower(0)
    end
end

-- 刷新公会属性信息
unionHandler.union_tech_attr_data = {} 
function unionHandler.GetUnionTechAttrValueByHeroTypeAndAttrId( hero_type, attr_id)
    local hero_attr_data = unionHandler.union_tech_attr_data[hero_type]
    if hero_attr_data ~= nil and hero_attr_data[attr_id] ~= nil then
        return hero_attr_data[attr_id]
    end

    return 0
end

function unionHandler.GetUnionTechAttrValueByHeroType( hero_type)
    local hero_attr_data = unionHandler.union_tech_attr_data[hero_type]
    if hero_attr_data ~= nil then
        return hero_attr_data
    end 
    return
end

-- 判断是否可以升级
function unionHandler.CanUpLevelGuildSkill()
    if unionHandler.cfg_guildskill_map == nil then
        unionHandler.cfg_guildskill_map = {}
        unionHandler.cfg_guildskill = G.dataTable["t_guildskill"]
        for _, v in pairs(unionHandler.cfg_guildskill) do
            if v ~= nil then
                if unionHandler.cfg_guildskill_map[v.f_ProfessionalType] == nil then
                    unionHandler.cfg_guildskill_map[v.f_ProfessionalType] = {}
                end
                if unionHandler.cfg_guildskill_map[v.f_ProfessionalType][v.f_SkillClass] == nil then
                    unionHandler.cfg_guildskill_map[v.f_ProfessionalType][v.f_SkillClass] = {}
                end
                unionHandler.cfg_guildskill_map[v.f_ProfessionalType][v.f_SkillClass][v.f_SkillLevel] = v
            end
        end
    end

    if unionHandler.cfg_guildskill == nil then
        unionHandler.cfg_guildskill = G.dataTable["t_guildskill"] or require("Data/t_guildskill")
    end
    local count = 0
    local attr_data = nil
    local attr_id = nil
    local tech_item = nil
    local skill_level_list = nil
    local hero_type = nil
    for k, v in pairs(unionHandler.union_tech_list_data) do
        tech_item = unionHandler.cfg_guildskill[tostring(v.techId + v.lv)]
        if tech_item ~= nil then
            hero_type = tech_item.f_ProfessionalType
            skill_level_list = unionHandler.cfg_guildskill_map[hero_type][tech_item.f_SkillClass]
            if skill_level_list ~= nil and skill_level_list[tech_item.f_SkillLevel+1] ~= nil and skill_level_list[tech_item.f_SkillLevel] ~= nil then
                local tb_cost_item = decodeJsonStrToTabel(skill_level_list[tech_item.f_SkillLevel]["f_Cost"])
                if tb_cost_item ~= nil and next(tb_cost_item) ~= nil and  tb_cost_item[1] ~= nil and next(tb_cost_item[1]) ~= nil then
                    local enough = true
                    for _, v in pairs(tb_cost_item) do
                        if logicMgr.ItemManager.getBagNumByTableID(v[1]) < tonumber(v[2]) then
                             enough = false
                             break
                        end
                    end
                    if enough then
                        return true
                    end
                end
            end
        end
    end 
    return false
end


unionHandler.cfg_guildskill_map = nil
function unionHandler.refreshUnionTechAttr()
    if unionHandler.cfg_guildskill_map == nil then
        unionHandler.cfg_guildskill_map = {}
        unionHandler.cfg_guildskill = G.dataTable["t_guildskill"]
        for _, v in pairs(unionHandler.cfg_guildskill) do
            if v ~= nil then
                if unionHandler.cfg_guildskill_map[v.f_ProfessionalType] == nil then
                    unionHandler.cfg_guildskill_map[v.f_ProfessionalType] = {}
                end
                if unionHandler.cfg_guildskill_map[v.f_ProfessionalType][v.f_SkillClass] == nil then
                    unionHandler.cfg_guildskill_map[v.f_ProfessionalType][v.f_SkillClass] = {}
                end
                unionHandler.cfg_guildskill_map[v.f_ProfessionalType][v.f_SkillClass][v.f_SkillLevel] = v
            end
        end
    end

    local count = 0
    local attr_data = nil
    local attr_id = nil
    local tech_item = nil
    local skill_level_list = nil
    local hero_type = nil
    unionHandler.union_tech_attr_data = {}
    for k, v in pairs(unionHandler.union_tech_list_data) do
        tech_item = unionHandler.cfg_guildskill[tostring(v.techId + v.lv)]
        hero_type = tech_item.f_ProfessionalType
        skill_level_list = unionHandler.cfg_guildskill_map[hero_type][tech_item.f_SkillClass]
        if unionHandler.union_tech_attr_data[hero_type] == nil then
           unionHandler.union_tech_attr_data[hero_type] = {}
        end 
        if skill_level_list[tech_item.f_SkillLevel+1] == nil and skill_level_list[tech_item.f_SkillLevel] ~= nil then
            attr_data = skill_level_list[tech_item.f_SkillLevel].f_AditionalAttribute
            attr_id = attr_data[1]
            if unionHandler.union_tech_attr_data[hero_type][attr_id] == nil then
                unionHandler.union_tech_attr_data[hero_type][attr_id] = 0
            end
            unionHandler.union_tech_attr_data[hero_type][attr_id] = 
                    unionHandler.union_tech_attr_data[hero_type][attr_id] + attr_data[2]
        end
        for i = 0, tech_item.f_SkillLevel do
            if skill_level_list[i] ~= nil then
                attr_data = skill_level_list[i].f_Attribute
                attr_id = attr_data[1]
                if unionHandler.union_tech_attr_data[hero_type][attr_id] == nil then
                    unionHandler.union_tech_attr_data[hero_type][attr_id] = 0
                end
                unionHandler.union_tech_attr_data[hero_type][attr_id] = 
                    unionHandler.union_tech_attr_data[hero_type][attr_id] + attr_data[2]
            end
        end
    end
end

--请求升级 
function unionHandler.sendReqUnionUpgradeTech( tech_id, num)
    --print("unionHandler.sendReqUnionUpgradeTech-->", tech_id, num)
    local req = ReqUnionUpgradeTechMessage.New()
    req.techId = tech_id -- tech_id 科技id
    req.num = num -- num 升级次数
    sendReqMessage(req)
end
-- 应答升级
function unionHandler.receiveResUnionUpgradeTech( msg )
    --print("unionHandler.receiveResUnionUpgradeTecho>", table.tostring(msg) )
    if msg and msg.state == 0 then
        local tech = msg.tech
        local key = tech.techId --+ tech.lv 
        if unionHandler.union_tech_list_data == nil then
            unionHandler.union_tech_list_data = {}
        end 
        unionHandler.union_tech_list_data[key] = tech 
        unionHandler.refreshUnionTechAttr()

        if isOpenUI(PanelNames.UIGuildTech) then
            local ui_guild_tech = CtrlManager.GetCtrl(PanelNames.UIGuildTech) 
            ui_guild_tech.UpdateUnionUpgradeTechResult(msg) ---- 应答科技列表数据
        end
        FireEvent(Config.EventType.Fresh_Guild_Tech)
    end
end

--请求重置 
function unionHandler.sendReqUnionResetTech( layer_id, job_id)
    --print("unionHandler.sendReqUnionResetTech->", layer_id, job_id)
    local req = ReqUnionResetTechMessage.New()
    req.layerId = layer_id -- 层级id
    req.jobId = job_id  -- 职业id
    sendReqMessage(req)
end
-- 返回重置结果
function unionHandler.receiveResUnionResetTech( msg )
    --print("unionHandler.receiveResUnionTechInfo>", table.tostring(msg) )
    if msg and msg.state == 0 then
        local key = nil 
        for _, v in pairs(msg.techs) do
            key = v.techId --+ v.lv
            if unionHandler.union_tech_list_data == nil then
                unionHandler.union_tech_list_data = {}
            end 
            unionHandler.union_tech_list_data[key] = v
        end

        unionHandler.refreshUnionTechAttr()

        if isOpenUI(PanelNames.UIGuildTech) then
            local ui_guild_tech = CtrlManager.GetCtrl(PanelNames.UIGuildTech) 
            ui_guild_tech.UpdateUnionResetTechResult(msg) ---- 返回重置结果
        end
        FireEvent(Config.EventType.Fresh_Guild_Tech)
    end
end

----------------------------------------------------
--- 工会任务相关逻辑
----------------------------------------------------
function unionHandler.sendReqUnionTaskListInfo()
    local req = ReqGuildTaskListInfoMessage.New()
    sendReqMessage(req)
end

function unionHandler.receiveResUnionTaskListInfo(msg)
    if msg and msg.state == 0 then
        logicMgr.GuildManager.taskLivenessCount = msg.liveness
        logicMgr.GuildManager.taskLivenessList = msg.recvBoxs
        --logicMgr.GuildManager.nextTaskResetTime = tonumber(msg.nextWeekResetTime)
        local t = tonumber(msg.nextWeekResetTime)
        logicMgr.GuildManager.OpenTaskResetTimer(tonumber(tostring(msg.nextWeekResetTime))/1000)
        for k,v in pairs(msg.taskList) do
            for m, n in pairs(logicMgr.GuildManager.taskInfoList) do
                if v.taskId == n.f_GuildTaskId then
                    n["progress"] = v.process
                    if v.recvStatus == 1 then  --0:可领取 1:未完成 2:已领取
                        n["status"] = 2
                    else
                        if v.process >= n.f_Progress then
                            n["status"] = 0
                        else
                            n["status"] = 1
                        end
                    end
                end
            end
        end
        FireEvent(Config.EventType.Fresh_Guild_Task)
    end
end

function unionHandler.sendReqUnionTaskAward(taskId)
    local req = ReqRecvGuildTaskAwardMessage.New()
    req.taskId = taskId -- 任务id
    sendReqMessage(req)
end

function unionHandler.receiveResUnionTaskAward(msg)
    if msg and msg.state == 0 then
        logicMgr.GuildManager.taskLivenessCount = msg.liveness
        for m, n in pairs(logicMgr.GuildManager.taskInfoList) do
            if msg.taskId == n.f_GuildTaskId then
                n["status"] = 2 --0:可领取 1:未完成 2:已领取
            end
        end
        FireEvent(Config.EventType.Fresh_Guild_Task)
    end
end

function unionHandler.sendReqUnionTaskBoxAward(boxId)
    local req = ReqRecvGuildTaskBoxAwardMessage.New()
    req.awardId = boxId -- 宝箱id
    sendReqMessage(req)
end

function unionHandler.receiveResUnionTaskBoxAward(msg)
    if msg and msg.state == 0 then
        logicMgr.GuildManager.ReceiveOneTaskBoxAward(msg.awardId)
        showUI(PanelNames.UICommonItemGet,nil,nil,2,msg.items)
        FireEvent(Config.EventType.Fresh_Guild_Task)
    end
end

function unionHandler.sendReqAllGuildTaskAward()
    local req = ReqRecvAllGuildTaskAwardMessage.New()
    sendReqMessage(req)
end

function unionHandler.receiveReAllGuildTaskAward(msg)
    if msg and msg.state == 0 then
        logicMgr.GuildManager.taskLivenessCount = msg.liveness
        for k,v in pairs(msg.taskIds) do
            for m, n in pairs(logicMgr.GuildManager.taskInfoList) do
                if v == n.f_GuildTaskId then
                    n["status"] = 2 --0:可领取 1:未完成 2:已领取
                end
            end
        end
        for k,v in pairs(msg.recvBoxs) do
            logicMgr.GuildManager.ReceiveOneTaskBoxAward(v)
        end
        if msg.items and #msg.items > 0 then
            showUI(PanelNames.UICommonItemGet,nil,nil,2,msg.items)
        end
        FireEvent(Config.EventType.Fresh_Guild_Task)
    end
end